package action;

import java.io.File;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;

import javax.print.attribute.standard.Severity;
import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;

import org.apache.commons.io.FileUtils;
import org.apache.struts2.ServletActionContext;
import org.apache.struts2.interceptor.RequestAware;
import org.apache.struts2.interceptor.SessionAware;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.User;

import pojo.Cart;
import pojo.Category;
import pojo.Offer;
import pojo.Overview;
import pojo.Product;
import pojo.ProductImage;
import pojo.Roles;
import pojo.Specification;
import pojo.UserProfile;

import com.opensymphony.xwork2.ActionSupport;

import dao.CarrierDAO;
import dao.CartDAO;
import dao.CategoryDAO;
import dao.DeviceBrandDAO;
import dao.OperatingSystemDAO;
import dao.ProductDAO;
import dao.RoleDAO;
import dao.UserDAO;

public class AdminAction extends ActionSupport implements RequestAware, SessionAware {

	private static final long serialVersionUID = 3362193580245212065L;
	private Map<String, Object> request;
	private Map<String, Object> session;

	@Autowired
	private UserDAO UserDAO;
	@Autowired
	private RoleDAO RoleDAO;
	@Autowired
	private ProductDAO ProductDAO;
	@Autowired
	private CategoryDAO CategoryDAO;
	@Autowired
	private DeviceBrandDAO DeviceBrandDAO;
	@Autowired
	private CarrierDAO CarrierDAO;
	@Autowired
	private OperatingSystemDAO OperatingSystemDAO;
	@Autowired
	private dao.OfferDAO OfferDAO;
	@Autowired
	private CartDAO CartDAO;
	

	// ===========================================
	public void setSession(Map<String, Object> arg0) {
		this.session = arg0;
	}

	public void setRequest(Map<String, Object> arg0) {
		this.request = arg0;
	}

	// =============================================
	
	private String action = "";

	// ============================= ADMIN USER =======================================
	private int id;
	private String idcart;
	private String sku = "";
	private Product product = null;	
	private UserProfile userProfile;
	private String rePassword = null;
	private String reEmail = null;
	private String email = "";
	private String btnsubmit = "";
	private int roles = 1;
	private String category = "";
	private int devicebrand = 1;
	private int carrier = 1;
	private int os = 1;
	private boolean active;
	private boolean available;

	public String execute() {
		request.put("userProfiles", UserDAO.getAllUser());
		return "success";
	}

	public String index() {
		return "viewuserlist";
	}
	
	public String userlist() {
		HttpServletRequest _request = ServletActionContext.getRequest();
		if (btnsubmit.equals("SubmitNew")) {

			if (_request.getParameter("roles") != null)
				roles = Integer.parseInt(_request.getParameter("roles"));

			if (userProfile.getFirstName() == null
					|| userProfile.getLastName() == null
					|| userProfile.getEmail() == null
					|| userProfile.getZipcode() == null
					|| userProfile.getPhoneNumber() == null
					|| rePassword == null || reEmail == null
					|| userProfile.getFirstName().isEmpty()
					|| userProfile.getLastName().isEmpty()
					|| userProfile.getEmail().isEmpty()
					|| userProfile.getZipcode().isEmpty()
					|| userProfile.getPhoneNumber().isEmpty()
					|| rePassword.isEmpty() || reEmail.isEmpty()) {
				request.put("errorregister",
						"All fields must be are required !!!");
				setRequestUser();
				return "newuserlist";
			}

			if (!userProfile.getPassword().equals(rePassword)) {
				request.put("errorregister",
						"Password does not match RePassword !!!");
				setRequestUser();
				return "newuserlist";
			}

			if (!userProfile.getEmail().equals(reEmail)) {
				request.put("errorregister", "Email does not match ReEmail !!!");
				setRequestUser();;
				return "newuserlist";
			}

			if (!UserDAO.addUserProfile(userProfile, active, roles)) {
				request.put("errorregister", "Email is already exist !!!");
				setRequestUser();
				return "newuserlist";
			}

			request.put("userProfiles", UserDAO.getAllUser());
			return "viewuserlist";
		}

		if (btnsubmit.equals("SubmitEdit")) {
			if (_request.getParameter("roles") != null)
				roles = Integer.parseInt(_request.getParameter("roles"));

			if (userProfile.getFirstName() == null
					|| userProfile.getLastName() == null
					|| userProfile.getEmail() == null
					|| userProfile.getZipcode() == null
					|| userProfile.getPhoneNumber() == null
					|| userProfile.getFirstName().isEmpty()
					|| userProfile.getLastName().isEmpty()
					|| userProfile.getEmail().isEmpty()
					|| userProfile.getZipcode().isEmpty()
					|| userProfile.getPhoneNumber().isEmpty()) {
				request.put("errorregister", "All fields must be are required !!!");
				setRequestUser();
				return "edituserlist";
			}
			
			if (  ((User)SecurityContextHolder.getContext().getAuthentication().getPrincipal()).getUsername().equals(userProfile.getEmail()) )
			{
				UserProfile yourProfile = UserDAO.getUserProfile(((User)SecurityContextHolder.getContext().getAuthentication().getPrincipal()).getUsername());
				if ( active != yourProfile.getEnable() || roles != ((Roles)yourProfile.getRoleses().iterator().next()).getId() )
				{
					request.put("errorregister", "Can not change stace of active, role for your account.");
					setRequestUser();
					return "edituserlist";
				}
			}

			UserProfile tem = UserDAO.getUserProfile(userProfile.getEmail());
			tem.setFirstName(userProfile.getFirstName());
			tem.setLastName(userProfile.getLastName());
			tem.setZipcode(userProfile.getZipcode());
			tem.setPassword(userProfile.getPassword());
			tem.setPhoneNumber(userProfile.getPhoneNumber());

			if (!UserDAO.updateUserProfile(tem, active, roles)) {
				request.put("errorregister", "Update failed !!!");
				setRequestUser();
				return "edituserlist";
			}

			request.put("userProfiles", UserDAO.getAllUser());
			return "viewuserlist";
		}

		if (action == "" || action.equals("view")) {
			request.put("userProfiles", UserDAO.getAllUser());
			return "viewuserlist";
		} else if (action.equals("new")) {
			if (userProfile == null) {
				request.put("roles", RoleDAO.getAllRoles());
				return "newuserlist";
			}

		} else if (action.equals("edit")) {
			request.put("curUser", UserDAO.getUserProfile(email));
			request.put("roles", RoleDAO.getAllRoles());
			return "edituserlist";
		} else if (action.equals("delete")) {
			userProfile = UserDAO.getUserProfile(id);
			if (  ((User)SecurityContextHolder.getContext().getAuthentication().getPrincipal()).getUsername().equals(userProfile.getEmail()) )
			{
				request.put("error", "Can not delete your account.");
			}
			else if ( UserDAO.deleteUserProfile(userProfile) == false )
			{
				request.put("error", "Error when delete (ex: a foreign key constraint fails)");
			}
			request.put("userProfiles", UserDAO.getAllUser());
			return "viewuserlist";
		}

		return "error";
	}

	// ============================= ADMIN PRODUCT =======================================
	public Overview overview;	
	public Specification specification;
	private List<File> fileUpload = new ArrayList<File>();
	private List<String> fileUploadContentType = new ArrayList<String>();
	private List<String> fileUploadFileName = new ArrayList<String>();
	
	public String productlist() {
		HttpServletRequest _request = ServletActionContext.getRequest();
		if (btnsubmit.equals("SubmitNew")) {

			if (_request.getParameter("category") != null)
				category = _request.getParameter("category");
			if (_request.getParameter("devicebrand") != null)
				devicebrand = Integer.parseInt(_request
						.getParameter("devicebrand"));
			if (_request.getParameter("carrier") != null)
				carrier = Integer.parseInt(_request.getParameter("carrier"));
			if (_request.getParameter("os") != null)
				os = Integer.parseInt(_request.getParameter("os"));

			if (product.getName() == null || product.getModel() == null
					|| product.getSku() == null || product.getPrice() == null
					|| product.getName().isEmpty()
					|| product.getModel().isEmpty()
					|| product.getSku().isEmpty()) {
				request.put("errorregister",
						"All fields must be are required !!!");
				request.put("curProduct", product);
				setRequestProduct();
				return "newproductlist";
			}
			
			if ( overview != null)
			{
				product.getOverviews().add(overview);
				overview.setProduct(product);
			}
			if ( specification != null)
			{
				product.getSpecifications().add(specification);
				specification.setProduct(product);
			}
			
			// Upload hinh tai vi tri nay
			List<ProductImage> productimages = new ArrayList<ProductImage>();
			if (fileUpload.size() > 0 && fileUploadContentType.size() > 0 && fileUploadFileName.size() > 0)
			{
				try {
					String repository = "products/";
					
					String filePath = _request.getSession().getServletContext().getRealPath("/");
		            filePath += repository;
		            
		            for ( int i = 0; i < fileUpload.size(); i++)
		            {
			            File fileToCreate = new File(filePath, fileUploadFileName.get(i));
			            FileUtils.copyFile(fileUpload.get(i), fileToCreate);
			            
			            int temp = fileToCreate.getPath().indexOf("products\\");
			            productimages.add( new ProductImage(null, fileToCreate.getPath().substring(temp)));
		            }
		            
		        } catch (Exception e) {
		            addActionError(e.getMessage());
		            
		            request.put("errorregister", "Upload file failed !!!");
					request.put("curProduct", product);
					setRequestProduct();
					return "newproductlist";
		        }
			}
			else
			{
				request.put("errorregister", "All fields must be are required !!!");
				request.put("curProduct", product);
				setRequestProduct();
				return "newproductlist";
			}
			
			if (!ProductDAO.addProduct(product, carrier, os, category, devicebrand, available, productimages))
			{
				request.put("errorregister", "Product is already exist !!!");
				request.put("curProduct", product);
				setRequestProduct();
				return "newproductlist";
			}

			request.put("products", ProductDAO.getAllProduct());
			return "viewproductlist";
		}

		//
		if (btnsubmit.equals("SubmitEdit")) {

			if (_request.getParameter("category") != null)
				category = _request.getParameter("category");
			if (_request.getParameter("devicebrand") != null)
				devicebrand = Integer.parseInt(_request
						.getParameter("devicebrand"));
			if (_request.getParameter("carrier") != null)
				carrier = Integer.parseInt(_request.getParameter("carrier"));
			if (_request.getParameter("os") != null)
				os = Integer.parseInt(_request.getParameter("os"));

			if (product.getName() == null || product.getModel() == null
					|| product.getSku() == null || product.getPrice() == null
					|| product.getName().isEmpty()
					|| product.getModel().isEmpty()
					|| product.getSku().isEmpty()) {
				request.put("errorregister",
						"All fields must be are required !!!");
				request.put("curProduct", product);
				setRequestProduct();
				return "editproductlist";
			}


			if ( overview != null)
			{
				product.getOverviews().add(overview);
				overview.setProduct(product);
			}
			if ( specification != null)
			{
				product.getSpecifications().add(specification);
				specification.setProduct(product);
			}
			
			
			if (!ProductDAO.updateProduct(product, carrier, os, category, devicebrand, available))

			{
				request.put("errorregister", "Update product failed !!!");
				request.put("curProduct", product);
				setRequestProduct();
				return "editproductlist";
			}

			request.put("products", ProductDAO.getAllProduct());
			return "viewproductlist";
		}
		
		if (action == "" || action.equals("view")) {
			request.put("products", ProductDAO.getAllProduct());
			
			return "viewproductlist";
		} else if (action.equals("new")) {
			setRequestProduct();
			return "newproductlist";
		} else if (action.equals("edit")) {
			Product p = ProductDAO.getProductBySKU(sku);
			request.put("curProduct", p);
			if(p.getOverviews().iterator().hasNext())
				request.put("overview", (Overview)p.getOverviews().iterator().next());
			if(p.getSpecifications().iterator().hasNext())
				request.put("specification", (Specification)p.getSpecifications().iterator().next());
			
			setRequestProduct();
			return "editproductlist";
		}else if(action.equals("delete")){
			product = ProductDAO.getProductBySKU(sku);
			ProductDAO.deleteProduct(product);

			request.put("products", ProductDAO.getAllProduct());
			return "viewproductlist";
		}

		return "error";
	}

	
	// ============================= ADMIN OFFER =======================================
	private Offer offer;
	
	private File imagePromotion;
	private String imagePromotionContentType;
	private String imagePromotionFileName;
	
	private File imageBanner;
	private String imageBannerContentType;
	private String imageBannerFileName;

	public String promotionlist() {
		
		HttpServletRequest _request = ServletActionContext.getRequest();
		
		if (btnsubmit.equals("SubmitNew")) {
			if (offer.getName() == null || offer.getDescription() == null
					|| offer.getName().isEmpty()
					|| offer.getDescription().isEmpty()) {
				request.put("errorregister", "All fields must be are required !!!");
				request.put("curPromotion", offer);
				
				return "newpromotionlist";
			}
			
			if ( imagePromotion != null && imagePromotionContentType != null && imagePromotionFileName != null)
			{
				try {
					String repository = "offer/";
					
					String filePath = _request.getSession().getServletContext().getRealPath("/");
		            filePath += repository;
		            
		            File fileToCreate = new File(filePath, imagePromotionFileName);
		            FileUtils.copyFile(imagePromotion, fileToCreate);
		            
		            int temp = fileToCreate.getPath().indexOf("offer\\");
		            offer.setImageUrl(fileToCreate.getPath().substring(temp));		            
		        } catch (Exception e) {
		            addActionError(e.getMessage());
		            request.put("curPromotion", offer);
		            request.put("errorregister", "Upload image promotion failed !!!");
					return "newpromotionlist";
		        }
			}
			
			if ( imageBanner != null && imageBannerContentType != null && imageBannerFileName != null)
			{
				try {
					String repository = "offer/banner";
					
					String filePath = _request.getSession().getServletContext().getRealPath("/");
		            filePath += repository;
		            
		            File fileToCreate = new File(filePath, imageBannerFileName);
		            FileUtils.copyFile(imageBanner, fileToCreate);
		            
		            int temp = fileToCreate.getPath().indexOf("offer\\");
		            offer.setImageBanner(fileToCreate.getPath().substring(temp));		            
		        } catch (Exception e) {
		            addActionError(e.getMessage());
		            request.put("errorregister", "Upload image banner failed !!!");
		            request.put("curPromotion", offer);
					return "newpromotionlist";
		        }
			}

			if (!OfferDAO.addOffer(offer, available)){
				request.put("errorregister", "Error !!! Can not create an promotion.");
				request.put("curPromotion", offer);
				return "newpromotionlist";
			}
			else
			{
				request.put("error", "Add promotion success !!!");
			}

			request.put("promotions", OfferDAO.getListOffer());
			return "viewpromotionlist";
		}
		
		
		if (btnsubmit.equals("SubmitEdit")) {
			if (offer.getName() == null || offer.getDescription() == null
					|| offer.getName().isEmpty()
					|| offer.getDescription().isEmpty()) {
				request.put("errorregister",
						"All fields must be are required !!!");
				request.put("curPromotion", offer);
				
				return "editpromotionlist";
			}

			
			if (!OfferDAO.updateOffer(offer, active))
			{
				request.put("errorregister", "Update promotion failed !!!");
				request.put("curPromotion", offer);
				// setRequestProduct();
				return "editpromotionlist";
			}

			request.put("promotions", OfferDAO.getListOffer());
			return "viewpromotionlist";
		}

		if (action == "" || action.equals("view")){
			request.put("promotions", OfferDAO.getListOffer());
			return "viewpromotionlist";
		}
		else if (action.equals("new"))
		{
			return "newpromotionlist";
		}
		else if (action.equals("edit"))
		{
			request.put("curPromotion", OfferDAO.getOfferFromId(id));
			return "editpromotionlist";
		}
		else if (action.equals("delete")) {
			
			offer = OfferDAO.getOfferFromId(id);
			if ( OfferDAO.deleteOffer(offer) == false )
			{
				request.put("error", "Error when delete !!!");
			}
			request.put("promotions", OfferDAO.getListOffer());
			return "viewpromotionlist";
		}
		return "error";
	}

	
	
	// ============================= ADMIN ORDER =======================================
	public int idcartdetail = -1;
	public int getIdcartdetail() {
		return idcartdetail;
	}

	public void setIdcartdetail(int idcartdetail) {
		this.idcartdetail = idcartdetail;
	}
	
	public String orderlist() {
		
		if (action == "" || action.equals("view")) {
			List<Cart> c = CartDAO.getAllCart();
			 request.put("orders", c);
			return "vieworderlist";
		}
		else if (action.equals("new"))
		{
			return "editorderlist";
		}
		else if (action.equals("edit")) {
			Cart c = CartDAO.getCartByID(idcart);
			request.put("idcart", idcart);
			request.put("cart", c);
			return "editorderlist";
		}
		
		/*if (action.equals("delete") && idcartdetail > -1)
		{
			if (CartDAO.deleteCartDetail(idcartdetail))
			{
				request.put("success", "Delete cart detail success.");
			}
			else
				request.put("error", "Can not delete cart detail !!!");
			
			return "editorderlist";
		}
		
		if (action.equals("delete") && idcart.isEmpty() == false)
		{
			
		}*/

		return "error";
	}
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	// ==========================================================================
	
	public String getAction() {
		return action;
	}
	public void setAction(String action) {
		this.action = action;
	}
	
	// Getter / Setter User
	
	private void setRequestUser(){
		request.put("curUser", userProfile);
		request.put("roles", RoleDAO.getAllRoles());
	}
	public int getId() {
		return id;
	}

	public void setId(int id) {
		this.id = id;
	}
	public void setIdcart(String idcart){
		this.idcart = idcart;
	}
	public void setSku(String sku) {
		this.sku = sku;
	}
	public Product getProduct(){
		return this.product;
	}
	
	public void setProduct(Product product) {
		this.product = product;
	}
	public UserProfile getUserProfile() {
		return userProfile;
	}

	public void setUserProfile(UserProfile userProfile) {
		this.userProfile = userProfile;
	}
	public void setRePassword(String rePassword) {
		this.rePassword = rePassword;
	}
	public void setReEmail(String reEmail) {
		this.reEmail = reEmail;
	}
	public void setEmail(String email) {
		this.email = email;
	}
	public void setBtnsubmit(String btnsubmit) {
		this.btnsubmit = btnsubmit;
	}
	public void setActive(boolean active) {
		this.active = active;
	}
	public void setAvailable(boolean available) {
		this.available = available;
	}
	
	// Getter / Setter Product
	
	private void setRequestProduct(){
		List<Category> categories = CategoryDAO.getListCategory();
		categories.remove(0);

		request.put("categories", categories);
		request.put("lstDeviceBrand",
				DeviceBrandDAO.getListDeviceBrand());
		request.put("lstCarrier", CarrierDAO.getListCarrier());
		request.put("lstOS", OperatingSystemDAO.getListOS());
	}
	public Overview getOverview() {
		return overview;
	}
	public void setOverview(Overview overview) {
		this.overview = overview;
	}
	public Specification getSpecification() {
		return specification;
	}
	public void setSpecification(Specification specification) {
		this.specification = specification;
	}
	public  List<File> getFileUpload() {
		return fileUpload;
	}
	public void setFileUpload( List<File> fileUpload) {
		this.fileUpload = fileUpload;
	}
	public List<String> getFileUploadContentType() {
		return fileUploadContentType;
	}
	public void setFileUploadContentType(List<String> fileUploadContentType) {
		this.fileUploadContentType = fileUploadContentType;
	}
	public List<String> getFileUploadFileName() {
		return fileUploadFileName;
	}
	public void setFileUploadFileName(List<String> fileUploadFileName) {
		this.fileUploadFileName = fileUploadFileName;
	}
	
	// Getter / Setter Promotion
	
	public File getImagePromotion() {
		return imagePromotion;
	}
	public void setImagePromotion(File imagePromotion) {
		this.imagePromotion = imagePromotion;
	}
	public String getImagePromotionContentType() {
		return imagePromotionContentType;
	}
	public void setImagePromotionContentType(String imagePromotionContentType) {
		this.imagePromotionContentType = imagePromotionContentType;
	}
	public String getImagePromotionFileName() {
		return imagePromotionFileName;
	}
	public void setImagePromotionFileName(String imagePromotionFileName) {
		this.imagePromotionFileName = imagePromotionFileName;
	}
	public Offer getOffer() {
		return offer;
	}
	public void setOffer(Offer offer) {
		this.offer = offer;
	}
	public File getImageBanner() {
		return imageBanner;
	}
	public void setImageBanner(File imageBanner) {
		this.imageBanner = imageBanner;
	}
	public String getImageBannerContentType() {
		return imageBannerContentType;
	}
	public void setImageBannerContentType(String imageBannerContentType) {
		this.imageBannerContentType = imageBannerContentType;
	}
	public String getImageBannerFileName() {
		return imageBannerFileName;
	}
	public void setImageBannerFileName(String imageBannerFileName) {
		this.imageBannerFileName = imageBannerFileName;
	}
	
}
